package com.wa.nashorn;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class ParkingNashornModuleApiServiceImpl implements NashornModuleApiService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ParkingNashornModuleApiServiceImpl.class);

    private static final long TIME_OUT = 100;//过期时间
    private static final String ALGORITHM = "RSA";
    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";

    private static final String MD5_WITH_RSA_ALGORITHM = "MD5withRSA";

//    static {
//        Security.addProvider(new BouncyCastleProvider());
//    }
//
//    @Autowired
//    ConfigurationProvider configProvider;
//
//    @Autowired
//    private ParkingService parkingService;
//
//    @Autowired
//    private FlowRpcService flowService;
//
//    @Autowired
//    private ParkingProvider parkingProvider;
//
//    @Autowired
//    private RechargeOrderProvider rechargeOrderProvider;
//
//    @Autowired
//    private RedisTemplateProvider redisTemplateProvider;
//
//    private static String signWithoutMD5(SortedMap<String, String> params) {
//        String restul = "";
//        if (params == null) {
//            return restul;
//        }
//
//        StringBuilder sb = new StringBuilder();
//        for (Map.Entry<String, String> me : params.entrySet()) {
//
//            sb.append(me.getKey());
//            sb.append('=');
//            sb.append(me.getValue());
//            sb.append('&');
//
//        }
//        int lastIndexOf = sb.lastIndexOf("&");
//        if (lastIndexOf != -1) {
//            sb.deleteCharAt(lastIndexOf);
//        }
//        restul = new String(sb);
//
//        return restul;
//    }
//
//    private static String sign(String content, String privateKey) {
//        try {
//            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
//            KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
//
//            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
//
//            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
//
//            signature.initSign(priKey);
//            signature.update(content.getBytes(StandardCharsets.UTF_8));
//
//            byte[] signed = signature.sign();
//
//            return Base64.encode(signed);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return null;
//    }
//
    @Override
    public String name() {
        return "parkingService";
    }

//    public List<ParkingRechargeRate> listParkingRechargeRates(Long id, String plateNumber, String cardType) {
//        ParkingLot parkingLot = parkingProvider.findParkingLotById(id);
//        List<ParkingRechargeRate> parkingRechargeRateList;
//        if (StringUtils.isBlank(plateNumber)) {
//            parkingRechargeRateList = parkingProvider.listParkingRechargeRates(parkingLot.getOwnerType(),
//                    parkingLot.getOwnerId(), parkingLot.getId(), null);
//        } else {
//            parkingRechargeRateList = parkingProvider.listParkingRechargeRates(parkingLot.getOwnerType(),
//                    parkingLot.getOwnerId(), parkingLot.getId(), cardType);
//        }
//        return parkingRechargeRateList;
//    }
//
//    public String getConfiguarationStringByName(String name) {
//        return configProvider.getValue(name, "");
//    }
//
//    public ParkingFlow getParkingFlow(GetOpenCardInfoCommand cmd) {
//        ParkingCardRequest parkingCardRequest = parkingProvider.findParkingCardRequestById(cmd.getParkingRequestId());
//
//        FlowCase flowCase = flowService.getFlowCaseById(parkingCardRequest.getFlowCaseId());
//
//        return parkingProvider.getParkingRequestCardConfig(cmd.getOwnerType(), cmd.getOwnerId(),
//                cmd.getParkingLotId(), flowCase.getFlowMainId());
//    }
//
//    public ParkingCardRequest getParkingCardRequestById(Long id) {
//        return parkingProvider.findParkingCardRequestById(id);
//    }
//
//    public ParkingCardRequest getParkingCardRequestByPlateNumber(String plateNumber) {
//        return parkingProvider.findParkingCardRequestByPlateNumber(plateNumber);
//    }
//
//    public ParkingCardRequest getParkingCardRequestByOrder(ParkingRechargeOrder order) {
//        List<ParkingCardRequest> list = new ArrayList<>();
//        if (ParkingPlateColor.fromCode(order.getPlateColor()) == ParkingPlateColor.YELLOW) {
//            String plateNumber = order.getPlateNumber().substring(0, 7);
//            list = parkingProvider.listParkingCardRequests(order.getCreatorUid(), order.getOwnerType(),
//                    order.getOwnerId(), order.getParkingLotId(), plateNumber,
//                    ParkingCardRequestStatus.SUCCEED.getCode(), null, null, null, null);
//        } else {
//            list = parkingProvider.listParkingCardRequests(order.getCreatorUid(), order.getOwnerType(),
//                    order.getOwnerId(), order.getParkingLotId(), order.getPlateNumber(),
//                    ParkingCardRequestStatus.SUCCEED.getCode(), null, null, null, null);
//        }
//
//        ParkingCardRequest parkingCardRequest = null;
//
//        for (ParkingCardRequest p : list) {
//            FlowCase flowCase = flowService.getFlowCaseById(p.getFlowCaseId());
//
//            Flow flow = flowService.findSnapshotFlow(flowCase.getFlowMainId(), flowCase.getFlowVersion());
//            ParkingLot parkingLot = parkingProvider.findParkingLotById(order.getParkingLotId());
//            Integer tag1 = parkingLot.getFlowMode();
//            if (null == tag1) {
//                throw RuntimeErrorException.errorWith(ErrorCodes.SCOPE_GENERAL, ErrorCodes.ERROR_GENERAL_EXCEPTION,
//                        "Flow tag is null.");
//            }
//            if (ParkingRequestFlowType.INTELLIGENT.getCode().equals(tag1)) {
//                parkingCardRequest = p;
//                break;
//            }
//        }
//
//        return parkingCardRequest;
//    }
//
//    public void updateParkingRechargeOrder(ParkingRechargeOrder order) {
//        rechargeOrderProvider.updateParkingRechargeOrder(order);
//    }
//
//    public void updateFlowStatus(ParkingCardRequest parkingCardRequest) {
//        UserDO user = UserContext.current().getUser();
//        LOGGER.debug("ParkingCardRequest pay callback user={}", user);
//
//        Tx.transaction(() -> {
//
//            if (null != parkingCardRequest) {
//                FlowCase flowCase = flowService.getFlowCaseById(parkingCardRequest.getFlowCaseId());
//
//                FlowAutoStepDTO stepDTO = new FlowAutoStepDTO();
//                stepDTO.setFlowCaseId(parkingCardRequest.getFlowCaseId());
//                stepDTO.setFlowMainId(flowCase.getFlowMainId());
//                stepDTO.setFlowVersion(flowCase.getFlowVersion());
//                stepDTO.setFlowNodeId(flowCase.getCurrentNodeId());
//                stepDTO.setAutoStepType(FlowStepType.APPROVE_STEP.getCode());
//                stepDTO.setStepCount(flowCase.getStepCount());
//                flowService.processAutoStep(stepDTO);
//
//                parkingCardRequest.setStatus(ParkingCardRequestStatus.OPENED.getCode());
//                parkingCardRequest.setOpenCardTime(new Timestamp(System.currentTimeMillis()));
//                parkingProvider.updateParkingCardRequest(parkingCardRequest);
//                //如果状态变为已开通,eh_parking_owner_cards 添加一条记录
//                createOwnerCard(parkingCardRequest, flowCase);
//                //如果状态变为已开通,eh_parking_recharge_date添加一条记录
//                parkingProvider.addParkingRechageDateByOpenStatus(parkingCardRequest,flowCase.getNamespaceId());
//            }
//        });
//    }
//
//    /**
//     * 添加月卡步骤
//     * 1: 判断月卡记录是否已添加
//     * 2: 根据停车场，车牌信息查询月卡信息
//     * 3: 新增月卡
//     * @param request
//     * @param flowCase
//     */
//    private void createOwnerCard(ParkingCardRequest request, FlowCase flowCase){
//        ParkingOwnerCard existsOwnerCard = parkingProvider.getParkingOwnerCard(request.getCreatorUid(), request.getPlateNumber());
//        if (existsOwnerCard != null) {
//            LOGGER.info(request.getPlateNumber() + "已有月卡,审批完成后不自动添加月卡");
//            return;
//        }
//        //向子系统请求月卡信息
////        ListParkingCardsCommand listParkingCardsCommand = new ListParkingCardsCommand();
////        listParkingCardsCommand.setPlateNumber(request.getPlateNumber());
////        listParkingCardsCommand.setPlateColor(request.getPlateColor());
////        listParkingCardsCommand.setParkingLotId(request.getParkingLotId());
////        listParkingCardsCommand.setOwnerId(request.getOwnerId());
////        listParkingCardsCommand.setOwnerType(request.getOwnerType());
////        List<ParkingCardDTO> parkingCards = parkingService.getParkingCards(listParkingCardsCommand);
////        if(CollectionUtils.isEmpty(parkingCards)){
////            LOGGER.info("请求子系统不存在月卡,{}", listParkingCardsCommand);
////            return;
////        }
//        ParkingOwnerCard parkingOwnerCard = new ParkingOwnerCard();
//        parkingOwnerCard.setRecordSource(ParkingOwnerCarResourceEnums.AUTO.getCode());
//        parkingOwnerCard.setNamespaceId(flowCase.getNamespaceId());
//        parkingOwnerCard.setOwnerId(request.getOwnerId());
//        parkingOwnerCard.setOwnerType(request.getOwnerType());
//        parkingOwnerCard.setParkingLotId(request.getParkingLotId());
//        parkingOwnerCard.setPlateNumber(request.getPlateNumber());
//        parkingOwnerCard.setPlateColor(request.getPlateColor());
//        parkingOwnerCard.setCardTypeId(request.getCardTypeId());
//        parkingOwnerCard.setCardTypeName(request.getCardTypeName());
//        parkingOwnerCard.setCreateUid(request.getCreatorUid());
//        parkingProvider.createParkingOwnerCard(parkingOwnerCard);
//    }
//
//    public Byte getCardStatus(Long parkingLotId, long expireTime, String cardTypeId) {
//        ParkingLot parkingLot = parkingProvider.findParkingLotById(parkingLotId);
//        ParkingRechargeRule rechargeRule =
//                parkingProvider.findParkingRechargeRuleByCardType(parkingLot.getOwnerType(), parkingLot.getOwnerId(),
//                        parkingLot.getId(), cardTypeId);
//        if (rechargeRule == null) {
//            ParkingCardRequestType type = new ParkingCardRequestType();
//            type.setCardTypeId(cardTypeId);
//            type.setOwnerId(parkingLot.getOwnerId());
//            type.setOwnerType(parkingLot.getOwnerType());
//            type.setParkingLotId(parkingLot.getId());
//            rechargeRule = getAndSetDefaultParkingRechargeRule(type);
//        }
//        long now = System.currentTimeMillis();
//
//        Byte status = ParkingCardStatus.NORMAL.getCode();
//
//        if (expireTime < now) {
//            status = ParkingCardStatus.EXPIRED.getCode();
//            if (Objects.equals(rechargeRule.getExpiredRechargeFlag(), ParkingConfigFlag.SUPPORT.getCode())) {
//                Integer cardReserveDay = rechargeRule.getMaxExpiredDay();
//                long cardReserveTime = cardReserveDay * 24 * 60 * 60 * 1000L;
//                if (expireTime + cardReserveTime >= now) {
//                    status = ParkingCardStatus.SUPPORT_EXPIRED_RECHARGE.getCode();
//                }
//            }
//        }
//        return status;
//    }
//
//    public String getTimestampStickToMonthEnd(Long startTime, Integer monthCount) {
//        Timestamp time = Utils.getTimestampStickToMonthEnd(startTime, monthCount);
//        return time.toString();
//    }
//
//    /**
//     * 获取自然月的最后一天，monthCount为1的时候 为当前月的最后一天
//     *
//     * @param monthCount
//     * @return
//     */
//    public String getTimestampByThisNatureMonth(Long startTime, Integer monthCount) {
//        Timestamp time = Utils.getTimestampByThisNatureMonth(startTime, monthCount);
//        return time.toString();
//    }
//
//    /**
//     * 深圳湾规则
//     * 1-28日缴费1个月的，有效期至下月对应缴费日的前一天；
//     * 29日及之后缴费1个月的，按下一自然月完整天数扣减缴费当月剩余使用天数计算。
//     *
//     * @param startTime
//     * @param monthCount
//     * @return
//     */
//    public String getTimestampByAddDistanceMonthV2(Long startTime, Integer monthCount) {
//        Timestamp time = Utils.getTimestampByAddDistanceMonthV2(startTime, monthCount);
//        return time.toString();
//    }
//
//    public ParkingLot getParkingLotById(Long parkingLotId) {
//        return parkingProvider.findParkingLotById(parkingLotId);
//    }
//
//    public String longToStr(Long time) {
//        Timestamp strTime = new Timestamp(time);
//        return strTime.toString();
//    }
//
//    public ParkingCardRequest findParkingCardRequestByParkingLotIdAndPlateNumber(Long parkingLotId,
//                                                                                 String plateNumber) {
//        return parkingProvider.findParkingCardRequestByParkingLotIdAndPlateNumber(parkingLotId, plateNumber);
//    }
//
//    public ParkingRechargeOrder getParkingRechargeOrderById(Long orderId) {
//        return rechargeOrderProvider.findParkingRechargeOrderById(orderId);
//    }
//
//    public void updateParkingRechargeOrderTime(ParkingRechargeOrder order, String startPeriod, String endPeriod) {
//        order.setStartPeriod(Timestamp.valueOf(startPeriod));
//        order.setEndPeriod(Timestamp.valueOf(endPeriod));
//        rechargeOrderProvider.updateParkingRechargeOrder(order);
//    }
//
//    @SuppressWarnings("unchecked")
//    public void setTokenCache(String key, String value) {
//        String redisKey = UserContext.getCurrentNamespaceId() + key;
//        RedisTemplate redisTemplate = redisTemplateProvider.getTemplate();
//        // 将token保存到缓存中，因第三方是120分钟，所以这里设置为100分钟
//        redisTemplate.opsForValue().set(redisKey, value, TIME_OUT, TimeUnit.MINUTES);
//    }
//
//    @SuppressWarnings("unchecked")
//    public String getTokenCache(String key) {
//        String redisKey = UserContext.getCurrentNamespaceId() + key;
//        RedisTemplate redisTemplate = redisTemplateProvider.getTemplate();
//        if (redisTemplate.opsForValue().get(redisKey) != null) {
//            return redisTemplate.opsForValue().get(redisKey).toString();
//        }
//        return null;
//    }
//
//    /**
//     * 获取规则
//     *
//     * @param ownerType
//     * @param ownerId
//     * @param parkingLotId
//     * @param cardType
//     * @return
//     */
//    public ParkingRechargeRule getParkingRechargeRule(String ownerType, Long ownerId, Long parkingLotId,
//                                                      String cardType) {
//        ParkingRechargeRule rechargeRule = parkingProvider.findParkingRechargeRuleByCardType(ownerType, ownerId,
//                parkingLotId, cardType);
//        if (rechargeRule == null) {
//            ParkingCardRequestType type = new ParkingCardRequestType();
//            type.setCardTypeId(cardType);
//            type.setOwnerId(ownerId);
//            type.setOwnerType(ownerType);
//            type.setParkingLotId(parkingLotId);
//            rechargeRule = getAndSetDefaultParkingRechargeRule(type);
//        }
//        return rechargeRule;
//    }
//
//    private ParkingRechargeRule getAndSetDefaultParkingRechargeRule(ParkingCardRequestType type) {
//        ParkingRechargeRule rechargeRule = ConvertHelper.convert(type, ParkingRechargeRule.class);
//        rechargeRule.setExpiredRechargeFlag(ParkingConfigFlag.NONSUPPORT.getCode());
//        rechargeRule.setCardType(type.getCardTypeId());
//        rechargeRule.setCardRequestMonthCount(2);
//        rechargeRule.setCardRequestRechargeType(ParkingCardExpiredRechargeType.ALL.getCode());
//        rechargeRule.setCardRequestRuleType(ParkingRechargeRuleType.RECHARGE_RATE.getCode());
//        parkingProvider.createParkingRechargeRule(rechargeRule);
//        return rechargeRule;
//    }
//
//    public ParkingLotGate checkParkingLotGate(Long gateId) {
//        if (null == gateId) {
//            LOGGER.error("GateId cannot be null.");
//            throw RuntimeErrorException.errorWith(ParkingErrorCode.SCOPE, ParkingErrorCode.PARAMTER_LOSE, "GateId " +
//                    "cannot be null.");
//        }
//
//        ParkingLotGate parkingLotGate = parkingProvider.findParkingLotGateById(gateId);
//        if (null == parkingLotGate) {
//            LOGGER.error("parkingLotGate not found, gateId={}", gateId);
//            throw RuntimeErrorException.errorWith(ParkingErrorCode.SCOPE, ParkingErrorCode.PARAMTER_LOSE,
//                    "parkingLotGate not found");
//        }
//        return parkingLotGate;
//    }
//
//    public String queryDataModelInfo(String jsonParamStr) {
//        JSONObject jsonParam = JSON.parseObject(jsonParamStr);
//        ApiResponse resp = AliyunIotApiHttpUtils.queryModelDataInfo(jsonParam.getString("appKey"),
//                jsonParam.getString("appSecret"), jsonParam.getString("apiVer"), jsonParam.getJSONObject("params"));
//        String ret = null;
//        if (null != resp) {
//            ret = new String(resp.getBody(), StandardCharsets.UTF_8);
//        }
//
//        return ret;
//    }
//
//    /**
//     * @param jsonParamStr
//     * @return
//     */
//    public String queryServiceModelInfo(String jsonParamStr) {
//        JSONObject jsonParam = JSON.parseObject(jsonParamStr);
//        ApiResponse resp = AliyunIotApiHttpUtils.queryServiceModelInfo(jsonParam.getString("appKey"),
//                jsonParam.getString("appSecret"), jsonParam.getString("apiVer"), jsonParam.getString("host"),
//                jsonParam.getString("path"), jsonParam.getBoolean("isHttps"), jsonParam.getJSONObject("params"));
//        String ret = null;
//        if (null != resp) {
//
//            ret = new String(resp.getBody(), StandardCharsets.UTF_8);
//        }
//
//        return ret;
//    }
//
//    public String checkAndSetOrderPrice(ParkingRechargeOrder order, Long parkingLotId, String ratePrice) {
//        ParkingLot parkingLot = parkingProvider.findParkingLotById(parkingLotId);
//        BigDecimal originalPrice = new BigDecimal(ratePrice);
//        if (null != parkingLot.getMonthlyDiscountFlag()) {
//            if (Objects.equals(parkingLot.getMonthlyDiscountFlag(), ParkingConfigFlag.SUPPORT.getCode())) {
//                originalPrice =
//                        originalPrice.multiply(new BigDecimal(parkingLot.getMonthlyDiscount())).divide(new BigDecimal(10), 2, RoundingMode.HALF_UP);
//            }
//        }
//        if (order.getPrice().compareTo(originalPrice) != 0) {
//            LOGGER.error("Invalid order price, orderPrice={}, ratePrice={}", order.getPrice(), ratePrice);
//            throw RuntimeErrorException.errorWith(ErrorCodes.SCOPE_GENERAL, ErrorCodes.ERROR_INVALID_PARAMETER,
//                    "Invalid order price.");
//        }
//        return originalPrice.toString();
//    }
//
//    //暂时只给五矿
//    public String getCarEntryInfo(Long parkingLotId, String plateNumber) {
//
//        return parkingService.getCarEntryInfo(parkingLotId, plateNumber);
//    }
//
//    @SuppressWarnings("unchecked")
//    public void setRedisCache(String key, String value, Long minutes) {
//        String redisKey = UserContext.getCurrentNamespaceId() + key;
//        RedisTemplate redisTemplate = redisTemplateProvider.getTemplate();
//        redisTemplate.opsForValue().set(redisKey, value, minutes, TimeUnit.MINUTES);
//    }
//
//    @SuppressWarnings("unchecked")
//    public String getRedisCache(String key) {
//        String redisKey = UserContext.getCurrentNamespaceId() + key;
//        RedisTemplate redisTemplate = redisTemplateProvider.getTemplate();
//        if (redisTemplate.opsForValue().get(redisKey) != null) {
//            return redisTemplate.opsForValue().get(redisKey).toString();
//        }
//        return null;
//    }
//
//    public String getSignForFujica(String privateKey, String json, String appSecret, String time) {
//        TreeMap<String, String> map = new TreeMap();
//        map.put("param", json);
//        map.put("secret", appSecret);
//        map.put("timestamp", time);
//        String sign = signWithoutMD5(map);
//        sign = sign(sign, privateKey);
//        return sign;
//    }
//
//    /**
//     * 达实停车V2版SHA-1加密方式
//     *
//     * @param str
//     * @return
//     */
//    public String sha1(String str) {
//        try {
//            //指定sha1算法
//            MessageDigest digest = MessageDigest.getInstance("SHA-1");
//            digest.update(str.getBytes());
//            //获取字节数组
//            byte[] messageDigest = digest.digest();
//            //创建 Hex String
//            StringBuilder hexString = new StringBuilder();
//            for (byte b : messageDigest) {
//                String shaHex = Integer.toHexString(b & 0xFF);
//                if (shaHex.length() < 2) {
//                    hexString.append(0);
//                }
//                hexString.append(shaHex);
//            }
//            return hexString.toString().toUpperCase();
//        } catch (NoSuchAlgorithmException e) {
//            throw RuntimeErrorException.errorWith(ParkingErrorCode.SCOPE_DASHI,
//                    ParkingErrorCode.ERROR_DASHI_GENERATE_SIGNATURE, "验签失败");
//        }
//    }
//
//    public String encryptBody(String version, String appID, String privateKey, String messageType, String data) throws InvalidKeyException {
//        String base64 = java.util.Base64.getEncoder().encodeToString(data.getBytes(StandardCharsets.UTF_8));
//        String subEncoded = StringUtils.substring(base64, 0, 50);
//
//        byte[] key = privateKey.getBytes(StandardCharsets.UTF_8);
//        byte[] keyBytes = Arrays.copyOf(key, 24);
//        byte[] bytes = new byte[0];
//        try {
//            bytes = des3EncodeECB(keyBytes, subEncoded.getBytes(StandardCharsets.UTF_8));
//        } catch (InvalidKeySpecException e) {
//            e.printStackTrace();
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        } catch (NoSuchPaddingException e) {
//            e.printStackTrace();
//        } catch (IllegalBlockSizeException e) {
//            e.printStackTrace();
//        } catch (BadPaddingException e) {
//            e.printStackTrace();
//        }
//
//        String unEncryptData = StringUtils.substring(base64, 50, base64.length());
//        String encryptData = java.util.Base64.getEncoder().encodeToString(bytes);
//
//        LocalDateTime localDateTime = LocalDateTime.now();
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        String timestamp = localDateTime.format(formatter);
//        String json = version + messageType + encryptData + appID + timestamp + privateKey;
//        String sign = DigestUtils.sha256Hex(json);
//
//        HashMap<String, String> map = new HashMap<>();
//        map.put("messageType", messageType);
//        map.put("actNumber", "");
//        map.put("encryptData", encryptData);
//        map.put("unEncryptData", unEncryptData);
//        map.put("sign", sign);
//        map.put("version", version);
//        map.put("timestamp", timestamp);
//        map.put("appID", appID);
//        return JSON.toJSONString(map);
//    }
//
//    public String decryptResult(String privateKey, String result) {
//        JSONObject response = JSON.parseObject(result);
//        String encryptData = response.getString("encryptData");
//
//        byte[] encrypt = java.util.Base64.getDecoder().decode(encryptData);
//
//        byte[] key = privateKey.getBytes(StandardCharsets.UTF_8);
//        byte[] keyBytes = Arrays.copyOf(key, 24);
//        byte[] bytes = new byte[0];
//        try {
//            bytes = des3DecodeECB(keyBytes, encrypt);
//        } catch (InvalidKeyException e) {
//            e.printStackTrace();
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        } catch (InvalidKeySpecException e) {
//            e.printStackTrace();
//        } catch (NoSuchPaddingException e) {
//            e.printStackTrace();
//        } catch (IllegalBlockSizeException e) {
//            e.printStackTrace();
//        } catch (BadPaddingException e) {
//            e.printStackTrace();
//        }
//
//        String unEncryptData = response.getString("unEncryptData");
//        byte[] data = java.util.Base64.getDecoder().decode(new String(bytes, StandardCharsets.UTF_8) + unEncryptData);
//        return new String(data, StandardCharsets.UTF_8);
//    }
//
//    /**
//     * ECB加密,不要IV
//     *
//     * @param key  密钥
//     * @param data 明文
//     * @return Base64编码的密文
//     * @throws Exception
//     */
//    public byte[] des3EncodeECB(byte[] key, byte[] data) throws InvalidKeyException, InvalidKeySpecException,
//            NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
//        DESedeKeySpec spec = new DESedeKeySpec(key);
//        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
//        Key secretKey = keyFactory.generateSecret(spec);
//
//        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
//
//        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
//
//        return cipher.doFinal(data);
//    }
//
//    /**
//     * ECB解密,不要IV
//     *
//     * @param key  密钥
//     * @param data 明文
//     * @throws Exception
//     */
//    public byte[] des3DecodeECB(byte[] key, byte[] data) throws InvalidKeyException, NoSuchAlgorithmException,
//            InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
//        DESedeKeySpec spec = new DESedeKeySpec(key);
//        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
//        Key secretKey = keyFactory.generateSecret(spec);
//
//        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
//
//        cipher.init(Cipher.DECRYPT_MODE, secretKey);
//
//        return cipher.doFinal(data);
//    }
//
//    /**
//     * AES解密 ECB模式 PKCS7Padding填充方式
//     *
//     * @param data 待解密数据
//     * @param key  密钥
//     * @return 解密后字符串
//     * @throws javax.crypto.NoSuchPaddingException    NoSuchPaddingException异常
//     * @throws NoSuchAlgorithmException               NoSuchAlgorithmException异常
//     * @throws java.security.InvalidKeyException      InvalidKeyException异常
//     * @throws javax.crypto.IllegalBlockSizeException IllegalBlockSizeException异常
//     * @throws javax.crypto.BadPaddingException       BadPaddingException异常
//     */
//    public String aes256ECBPkcs7PaddingDecrypt(String data, String key) throws NoSuchPaddingException,
//            NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
//        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
//        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
//        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, "AES"));
//        byte[] doFinal = cipher.doFinal(java.util.Base64.getDecoder().decode(data));
//        return new String(doFinal);
//    }
//
//    /**
//     * HmacSHA1加密
//     *
//     * @param data 待解密数据
//     * @param key  密钥
//     * @return 加密后字符串
//     */
//    public String hmacSHA1(String data, String key) {
//        byte[] doFinal = new HmacUtils(HmacAlgorithms.HMAC_SHA_1, key).hmac(data);
//        return java.util.Base64.getEncoder().encodeToString(doFinal);
//    }
//
//    public void initConfig(String host, String appKey, String appSecret) {
//        ArtemisConfig.host = host;
//        ArtemisConfig.appKey = appKey;
//        ArtemisConfig.appSecret = appSecret;
//    }
//
//    public String doPostStringArtemis(Map<String, String> path, String body) {
//        LOGGER.info("start http request, path={}, params={}", path, body);
//        String response = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, ContentType.CONTENT_TYPE_JSON,
//                null);
//        LOGGER.info("end http request, response={}", response);
//        return response;
//    }
//
//    public EhParkingEntryAndExitRecords getLatestParkingEntryAndExitRecord(Long parkingLotId, String plateNo) {
//        SearchParkingEntryAndExitRecordsCommand command = new SearchParkingEntryAndExitRecordsCommand();
//        command.setParkingLotId(parkingLotId);
//        if (StringUtils.isNotBlank(plateNo)) {
//            command.setPlateNumber(plateNo);
//        }
//        command.setPageAnchor(1);
//        command.setPageSize(1);
//        List<EhParkingEntryAndExitRecords> records = parkingProvider.listParkingEntryAndExitRecordsRecords(command);
//        if (CollectionUtils.isNotEmpty(records)) {
//            return records.get(0);
//        }
//        return null;
//    }
//
//    public void updateParkingEntryAndExitRecord(EhParkingEntryAndExitRecords record) {
//        parkingProvider.updateParkingEntryAndExitRecord(record);
//    }
//
//    public EhParkingEntryAndExitRecords findParkingEntryAndExitRecordByPlateNo(Long parkingLotId, String plateNo) {
//        return parkingProvider.findParkingEntryAndExitRecordByPlateNo(parkingLotId, plateNo);
//    }
//
//    public String generateNoPlateNo() {
//        if (UserContext.currentUserId() != null) {
//            return ParkingConstants.VIRTUAL_PLATE_NO_PREFIX + UserContext.currentUserId();
//        }
//        return "";
//    }
//
//    public ParkingRechargeOrder findParkingRechargeOrderByPlateNoAndRechargeType(Long parkingLotId, String plateNo,
//                                                                                 Byte rechargeType) {
//        return rechargeOrderProvider.findParkingRechargeOrderByPlateNoAndRechargeType(parkingLotId, plateNo,
//                rechargeType);
//    }
//
    public String md5Hex(String data) {
        return DigestUtils.md5Hex(data);
    }

//    /**
//     * 用私钥对信息生成数字签名
//     *
//     * @param data       数据
//     * @param privateKey 私钥(BASE64编码)
//     * @return String
//     * @throws Exception 异常
//     */
//    public String buildSignJson(String data, String privateKey) throws Exception {
//        byte[] keyBytes = java.util.Base64.getDecoder().decode(privateKey);
//        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
//        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
//        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
//        Signature signature = Signature.getInstance(MD5_WITH_RSA_ALGORITHM);
//        signature.initSign(privateK);
//        signature.update(data.getBytes());
//        return java.util.Base64.getEncoder().encodeToString(signature.sign());
//    }
}
